from typing import List, Dict, Any
from .database_tool import DatabaseTool
from .nlp_tool import NLPTool

class ProductTool:
    def __init__(self, db_tool: DatabaseTool, nlp_tool: NLPTool):
        self.db_tool = db_tool
        self.nlp_tool = nlp_tool

    def search_products(self, query: str) -> Dict[str, Any]:
        """根据用户查询搜索商品"""
        # 分析用户意图
        intent = self.nlp_tool.analyze_intent(query)
        products = []
        total_found = 0

        try:
            # 检测场景
            scene = intent.get("parameters", {}).get("scene")
            if not scene:
                # 如果意图分析没有检测到场景，尝试使用NLPTool的场景检测
                scene = self.nlp_tool.detect_scene_from_query(query)
            
            # 基于场景的商品推荐
            if scene:
                # 记录检测到的场景
                print(f"检测到场景: {scene}")
                
                # 获取场景相关的商品类别
                categories = self.nlp_tool.get_categories_for_scene(scene)
                print(f"场景相关类别: {categories}")
                
                # 获取场景相关的具体商品
                scene_products = self.nlp_tool.get_products_for_scene(scene)
                print(f"场景相关商品: {scene_products}")
                
                # 使用数据库工具的场景化查询 - 修复调用方式
                try:
                    # 根据场景搜索相关类别的商品
                    for category in categories:
                        category_products = self.db_tool.get_products_by_category(category)
                        if category_products:
                            # 去重添加
                            existing_ids = {p["id"] for p in products}
                            products.extend([p for p in category_products if p["id"] not in existing_ids])
                        if len(products) >= 10:  # 限制最多10个商品
                            break
                except Exception as e:
                    print(f"场景化查询出错: {str(e)}")
            
            # 根据商品类别搜索
            if not products and intent.get("parameters", {}).get("category"):
                category = intent["parameters"]["category"]
                print(f"按类别搜索: {category}")
                category_products = self.db_tool.get_products_by_category(category)
                if category_products:
                    products = category_products
            
            # 根据价格范围搜索
            if not products and intent.get("parameters", {}).get("price_range"):
                price_range = intent["parameters"]["price_range"]
                min_price = float(price_range.get("min", 0))
                max_price = float(price_range.get("max", 10000))
                print(f"按价格范围搜索: {min_price}-{max_price}")
                price_products = self.db_tool.get_products_by_price_range(min_price, max_price)
                if price_products:
                    products = price_products
            
            # 根据具体商品名称搜索
            if not products and intent.get("parameters", {}).get("product"):
                product_names = intent["parameters"]["product"]
                print(f"按商品名称搜索: {product_names}")
                if isinstance(product_names, list):
                    for product_name in product_names:
                        name_products = self.db_tool.search_products(product_name)
                        if name_products:
                            # 去重添加
                            existing_ids = {p["id"] for p in products}
                            products.extend([p for p in name_products if p["id"] not in existing_ids])
                else:
                    name_products = self.db_tool.search_products(product_names)
                    if name_products:
                        products = name_products
            
            # 如果还没有找到商品，使用关键词搜索
            if not products:
                print(f"关键词搜索: {query}")
                keyword_products = self.db_tool.search_products(query)
                if keyword_products:
                    products = keyword_products
            
            # 如果没有找到任何商品，但有场景信息，尝试基于场景的类别搜索
            if not products and scene:
                categories = self.nlp_tool.get_categories_for_scene(scene)
                print(f"基于场景类别搜索: {categories}")
                for category in categories:
                    category_products = self.db_tool.get_products_by_category(category)
                    if category_products:
                        # 去重添加
                        existing_ids = {p["id"] for p in products}
                        products.extend([p for p in category_products if p["id"] not in existing_ids])
                    if len(products) >= 10:  # 限制最多10个商品
                        break
            
            # 如果没有找到任何商品，返回热门商品
            if not products:
                print("获取热门商品")
                products = self.db_tool.get_popular_products(5)

            total_found = len(products)
            
            # 根据相关性和销量排序（如果有销量数据）
            if products and "total_sales" in products[0]:
                products.sort(key=lambda x: x.get("total_sales", 0), reverse=True)
            
            # 生成推荐文案
            if scene:
                # 使用场景特定的推荐文案生成
                recommendation_text = self.nlp_tool.generate_scene_specific_recommendation(scene, products)
            else:
                # 使用一般推荐文案生成
                recommendation_text = self.nlp_tool.generate_recommendation_text(products, query)

            return {
                "success": True,
                "message": recommendation_text,
                "data": {
                    "products": products[:5],  # 只返回前5个商品
                    "total_found": total_found,
                    "scene": scene
                }
            }

        except Exception as e:
            print(f"搜索商品时出错: {str(e)}")
            return {
                "success": False,
                "message": f"搜索商品时出错: {str(e)}",
                "data": None
            }

    def get_product_details(self, product_id: int) -> Dict[str, Any]:
        """获取商品详细信息"""
        try:
            product = self.db_tool.get_product_by_id(product_id)
            if not product:
                return {
                    "success": False,
                    "error": "商品不存在"
                }
            return {
                "success": True,
                "product": product
            }
        except Exception as e:
            return {
                "success": False,
                "error": str(e)
            }

    def get_popular_products(self, limit: int = 5) -> Dict[str, Any]:
        """获取热门商品"""
        try:
            products = self.db_tool.get_popular_products(limit)
            return {
                "success": True,
                "products": products
            }
        except Exception as e:
            return {
                "success": False,
                "error": str(e)
            }
    
    def get_scene_recommendations(self, scene: str, limit: int = 5) -> Dict[str, Any]:
        """获取场景推荐商品"""
        try:
            print(f"获取场景推荐: {scene}")
            
            # 获取场景相关的商品类别
            categories = self.nlp_tool.get_categories_for_scene(scene)
            print(f"场景相关类别: {categories}")
            
            # 获取场景相关的具体商品
            scene_products = self.nlp_tool.get_products_for_scene(scene)
            print(f"场景相关商品: {scene_products}")
            
            # 修复：不再使用self.db_tool.tool()方法，而是直接使用类别搜索
            products = []
            
            # 根据场景相关类别搜索商品
            if categories:
                for category in categories:
                    category_products = self.db_tool.get_products_by_category(category)
                    if category_products:
                        # 去重添加
                        existing_ids = {p["id"] for p in products}
                        products.extend([p for p in category_products if p["id"] not in existing_ids])
                    if len(products) >= limit:
                        break
            
            # 如果没有找到商品，尝试关键词搜索
            if not products:
                # 尝试使用场景名称作为关键词搜索
                keyword_products = self.db_tool.search_products(scene)
                if keyword_products:
                    products = keyword_products
            
            # 如果还是没有找到商品，返回热门商品
            if not products:
                products = self.db_tool.get_popular_products(limit)
            
            # 生成推荐文案
            recommendation_text = self.nlp_tool.generate_scene_specific_recommendation(
                scene, 
                products
            )
            
            return {
                "success": True,
                "message": recommendation_text,
                "data": {
                    "products": products[:limit],
                    "total_found": len(products),
                    "scene": scene
                }
            }
        except Exception as e:
            print(f"获取场景推荐商品时出错: {str(e)}")
            return {
                "success": False,
                "message": f"获取场景推荐商品时出错: {str(e)}",
                "data": None
            }
    
    def get_products_by_scene_and_category(self, scene: str, category: str, limit: int = 5) -> Dict[str, Any]:
        """获取特定场景和类别的商品"""
        try:
            print(f"获取场景和类别商品: 场景={scene}, 类别={category}")
            
            # 使用数据库工具查询
            products = self.db_tool.get_products_by_category(category)
            
            if not products:
                return {
                    "success": False,
                    "message": f"未找到{category}类别的商品",
                    "data": None
                }
            
            # 生成推荐文案
            recommendation_text = self.nlp_tool.generate_scene_specific_recommendation(
                scene, 
                products
            )
            
            return {
                "success": True,
                "message": recommendation_text,
                "data": {
                    "products": products[:limit],
                    "total_found": len(products),
                    "scene": scene,
                    "category": category
                }
            }
        except Exception as e:
            print(f"获取场景和类别商品时出错: {str(e)}")
            return {
                "success": False,
                "message": f"获取场景和类别商品时出错: {str(e)}",
                "data": None
            }
    
    # 添加新方法，与main.py中调用的方法名保持一致
    def get_products_by_category_and_scene(self, category: str, scene: str, limit: int = 5) -> Dict[str, Any]:
        """获取特定类别和场景的商品（重命名版本）"""
        return self.get_products_by_scene_and_category(scene, category, limit)
    
    def get_products_by_category(self, category: str, limit: int = 5) -> Dict[str, Any]:
        """获取特定类别的商品"""
        try:
            print(f"获取类别商品: 类别={category}")
            
            # 使用数据库工具查询
            products = self.db_tool.get_products_by_category(category)
            
            if not products:
                return {
                    "success": False,
                    "message": f"未找到{category}类别的商品",
                    "data": None
                }
            
            # 限制返回数量
            products = products[:limit]
            
            # 生成推荐文案
            recommendation_text = self.nlp_tool.generate_recommendation_text(
                products, 
                f"{category}类商品推荐"
            )
            
            return {
                "success": True,
                "message": recommendation_text,
                "data": {
                    "products": products,
                    "total_found": len(products),
                    "category": category
                }
            }
        except Exception as e:
            print(f"获取类别商品时出错: {str(e)}")
            return {
                "success": False,
                "message": f"获取类别商品时出错: {str(e)}",
                "data": None
            }
    
    def get_products_by_price_range(self, min_price: float, max_price: float, limit: int = 5) -> Dict[str, Any]:
        """获取特定价格范围的商品"""
        try:
            print(f"获取价格范围商品: {min_price}-{max_price}")
            
            # 使用数据库工具查询
            products = self.db_tool.get_products_by_price_range(min_price, max_price)
            
            if not products:
                return {
                    "success": False,
                    "message": f"未找到价格在{min_price}元至{max_price}元之间的商品",
                    "data": None
                }
            
            # 限制返回数量
            products = products[:limit]
            
            # 生成推荐文案
            recommendation_text = self.nlp_tool.generate_recommendation_text(
                products, 
                f"价格{min_price}元至{max_price}元的商品推荐"
            )
            
            return {
                "success": True,
                "message": recommendation_text,
                "data": {
                    "products": products,
                    "total_found": len(products),
                    "price_range": {"min": min_price, "max": max_price}
                }
            }
        except Exception as e:
            print(f"获取价格范围商品时出错: {str(e)}")
            return {
                "success": False,
                "message": f"获取价格范围商品时出错: {str(e)}",
                "data": None
            }
    
    def get_products_by_name(self, product_name: str, limit: int = 5) -> Dict[str, Any]:
        """获取匹配名称的商品"""
        try:
            print(f"获取名称匹配商品: {product_name}")
            
            # 使用数据库工具查询
            products = self.db_tool.search_products(product_name)
            
            if not products:
                return {
                    "success": False,
                    "message": f"未找到名称含有'{product_name}'的商品",
                    "data": None
                }
            
            # 限制返回数量
            products = products[:limit]
            
            # 生成推荐文案
            recommendation_text = self.nlp_tool.generate_recommendation_text(
                products, 
                f"{product_name}商品推荐"
            )
            
            return {
                "success": True,
                "message": recommendation_text,
                "data": {
                    "products": products,
                    "total_found": len(products),
                    "search_term": product_name
                }
            }
        except Exception as e:
            print(f"获取名称匹配商品时出错: {str(e)}")
            return {
                "success": False,
                "message": f"获取名称匹配商品时出错: {str(e)}",
                "data": None
            }
    
    def search_products_by_keywords(self, keywords: str, limit: int = 5) -> Dict[str, Any]:
        """根据关键词搜索商品"""
        try:
            print(f"关键词搜索商品: {keywords}")
            
            # 使用数据库工具查询
            products = self.db_tool.search_products(keywords)
            
            if not products:
                return {
                    "success": False,
                    "message": f"未找到与'{keywords}'相关的商品",
                    "data": None
                }
            
            # 限制返回数量
            products = products[:limit]
            
            # 生成推荐文案
            recommendation_text = self.nlp_tool.generate_recommendation_text(
                products, 
                keywords
            )
            
            return {
                "success": True,
                "message": recommendation_text,
                "data": {
                    "products": products,
                    "total_found": len(products),
                    "keywords": keywords
                }
            }
        except Exception as e:
            print(f"关键词搜索商品时出错: {str(e)}")
            return {
                "success": False,
                "message": f"关键词搜索商品时出错: {str(e)}",
                "data": None
            }

    def get_fitness_recommendations(self, query: str, limit: int = 5) -> Dict[str, Any]:
        """获取健身相关推荐商品"""
        try:
            print(f"获取健身推荐: {query}")
            
            # 分析用户意图，提取更多信息
            intent = self.nlp_tool.analyze_intent(query)
            
            # 确定健身子场景（如增肌、减脂等）
            sub_scene = None
            if "parameters" in intent and "scene" in intent["parameters"]:
                sub_scene = intent["parameters"]["scene"]
                if sub_scene not in ["健身", "增肌", "减肥", "瑜伽", "跑步", "游泳", "球类运动", "户外活动", "居家健身"]:
                    sub_scene = "健身"  # 默认为一般健身
            else:
                # 尝试从查询中检测子场景
                for scene in ["增肌", "减肥", "瑜伽", "跑步", "游泳", "球类运动", "户外活动", "居家健身"]:
                    if scene in query:
                        sub_scene = scene
                        break
                if not sub_scene:
                    sub_scene = "健身"  # 默认为一般健身
            
            print(f"健身子场景: {sub_scene}")
            
            # 获取场景相关的商品类别
            categories = self.nlp_tool.get_categories_for_scene(sub_scene)
            print(f"场景相关类别: {categories}")
            
            # 获取场景相关的具体商品
            scene_products = self.nlp_tool.get_products_for_scene(sub_scene)
            print(f"场景相关商品: {scene_products}")
            
            # 修复：直接使用类别搜索，不再使用self.db_tool.tool()
            products = []
            
            # 根据场景相关类别搜索商品
            if categories:
                for category in categories:
                    category_products = self.db_tool.get_products_by_category(category)
                    if category_products:
                        # 去重添加
                        existing_ids = {p["id"] for p in products}
                        products.extend([p for p in category_products if p["id"] not in existing_ids])
                    if len(products) >= limit:
                        break
            
            # 如果没有找到商品，尝试关键词搜索
            if not products:
                # 尝试使用场景名称和关键词组合搜索
                keywords = [sub_scene, "健身", "运动"]
                for keyword in keywords:
                    keyword_products = self.db_tool.search_products(keyword)
                    if keyword_products:
                        # 去重添加
                        existing_ids = {p["id"] for p in products}
                        products.extend([p for p in keyword_products if p["id"] not in existing_ids])
                    if len(products) >= limit:
                        break
            
            # 如果还是没有找到商品，返回热门商品
            if not products:
                products = self.db_tool.get_popular_products(limit)
            
            # 生成推荐文案
            recommendation_text = self.nlp_tool.generate_scene_specific_recommendation(
                sub_scene, 
                products
            )
            
            return {
                "success": True,
                "message": recommendation_text,
                "data": {
                    "products": products[:limit],
                    "total_found": len(products),
                    "scene": sub_scene
                }
            }
        except Exception as e:
            print(f"获取健身推荐商品时出错: {str(e)}")
            return {
                "success": False,
                "message": f"获取健身推荐商品时出错: {str(e)}",
                "data": None
            }
    
    # 添加一个新方法，用于直接搜索特定类别的商品
    def search_products_by_category_list(self, categories: List[str], limit: int = 5) -> List[Dict]:
        """根据类别列表搜索商品"""
        products = []
        for category in categories:
            category_products = self.db_tool.get_products_by_category(category)
            if category_products:
                # 去重添加
                existing_ids = {p["id"] for p in products}
                products.extend([p for p in category_products if p["id"] not in existing_ids])
            if len(products) >= limit:
                break
        return products[:limit]